package com.bocai.grainshop.product.exception;

import com.bocai.common.exception.CodeMnume;
import com.bocai.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//统一处理异常的类
@Slf4j
@RestControllerAdvice(basePackages = "com.bocai.grainshop.product.controller")
public class grainshopExceptionControllerAdvice {

    //捕获数据异常
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handVialdException(MethodArgumentNotValidException e){
        log.error("数据异常！！",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        }));
        return R.error(400,"数据校验异常").put("data",map);
    }

    //捕获任意的异常
//    @ExceptionHandler(value = Throwable.class)
//    public R HandException(){
//        return R.error(CodeMnume.UNKNOW_EXCEPTION.getCode(),CodeMnume.UNKNOW_EXCEPTION.getMessage());
//    }
}
